package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.PowerTreasure;
import com.ruoyi.web.controller.tool.DateDifference;
import com.ruoyi.web.controller.tool.FeeCalculator;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PowerOrder;
import com.ruoyi.system.service.IPowerOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单表Controller
 * 
 * @author ljl
 * @date 2025-03-21
 */
@RestController
@RequestMapping("/system/order")
public class PowerOrderController extends BaseController
{
    @Autowired
    private IPowerOrderService powerOrderService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询订单表列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(PowerOrder powerOrder)
    {
        startPage();
        List<PowerOrder> list = powerOrderService.selectPowerOrderList(powerOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单表列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @Log(title = "订单表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PowerOrder powerOrder)
    {
        List<PowerOrder> list = powerOrderService.selectPowerOrderList(powerOrder);
        ExcelUtil<PowerOrder> util = new ExcelUtil<PowerOrder>(PowerOrder.class);
        util.exportExcel(response, list, "订单表数据");
    }

    /**
     * 获取订单表详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        return success(powerOrderService.selectPowerOrderByOrderId(orderId));
    }

    /**
     * 新增订单表
     */
    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "订单表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PowerOrder powerOrder)
    {
        return toAjax(powerOrderService.insertPowerOrder(powerOrder));
    }
    /**
     * 租借
     */
    @PreAuthorize("@ss.hasPermi('order:treasure:rent')")
    @Log(title = "租借", businessType = BusinessType.INSERT)
    @PostMapping("/rent")
    public AjaxResult rent(@RequestBody PowerOrder powerOrder)
    {
        // 生成订单号
        powerOrder.setOrderNumber(generateOrderNumber());
        // 当前用户id
        powerOrder.setUserId(SecurityUtils.getUserId());
        // 订单状态
        powerOrder.setOrderStatus(0l);
        // 开始时间
        powerOrder.setStartTime(new Date());

        return toAjax(powerOrderService.rent(powerOrder));
    }
    /**
     * 生成订单号
     */
    public String generateOrderNumber() {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
        //根据当前时间获取yyMMdd格式的时间字符串
        String format = LocalDate.now().format(formatter);
        //判断是否存在key，不存在则设置1天的过期时间
        if (Boolean.FALSE.equals(redisTemplate.hasKey(format))) {
            redisTemplate.expire(format, 1, TimeUnit.DAYS);
        }
        //使用incr获取自增的订单号
        Long increment = redisTemplate.opsForValue().increment(format);
        //将订单号不足4位前缀补0，"%04d"，%0表示前缀补0，4表示补充4位，d表示数字类型
        String oderCode = String.format("%04d", increment);
        return format + oderCode;
    }
    @GetMapping("/end")
    @PreAuthorize("@ss.hasPermi('system:order:end')")
    public AjaxResult endOrder(long orderId, long treasureId) {
        // 根据id获取订单信息
        PowerOrder order = powerOrderService.selectPowerOrderByOrderId(orderId);
        order.setEndTime(new Date());
        // 获取使用的分钟数
        long diffMinites = DateDifference.diff(order.getStartTime(), order.getEndTime());
        // 计算费用
        BigDecimal fee = FeeCalculator.calculateFee2(diffMinites);

        order.setDuration(diffMinites);
        order.setOrderStatus(1l);
        order.setAccount(fee);

        PowerTreasure powerTreasure = new PowerTreasure();
        powerTreasure.setTreasureId(treasureId);
        powerTreasure.setRentalStatus(1l);


        return toAjax(powerOrderService.endOrder(order, powerTreasure));
    }

    /**
     * 修改订单表
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "订单表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PowerOrder powerOrder)
    {
        return toAjax(powerOrderService.updatePowerOrder(powerOrder));
    }

    /**
     * 删除订单表
     */
    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "订单表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        return toAjax(powerOrderService.deletePowerOrderByOrderIds(orderIds));
    }
}
